import {ref, computed, watch} from 'vue'
import {defineStore} from 'pinia'
import { getCartListApi } from '@/api'
import { useUserStore } from '@/stores'

export const useCartStore = defineStore('cart', () => {
  // 购物车列表
  const cartList = ref([])
  // 总金额
  const total_price = ref(0)
  // 实付款
  const payment = ref(0)
  // 积分抵扣金额
  const discount = ref(0)
  // 购物车数量
  const cartNum = computed(() => {
    let num = 0
    if (cartList.value.length) cartList.value.forEach(item => {
      item.goods.forEach((good) => num = num + good.num )
    })
    return num
  })
  // 选中的商品信息
  const selectedInfo= computed(() => {
    let info = {
      num: 0, // 选中的商品数量
      sku: [], // 选中的商品sku
      goods: [], // 选中的商品
      createOrder: [], // 下单所需的信息
    }
    if (cartList.value.length) cartList.value.forEach(item => {
      item.goods.forEach((good) => {
        if (good.checked) {
          info.sku.push(good.sku)
          info.goods.push(good)
          info.num = good.num + info.num
          info.createOrder.push({
            goods_item_id: good?.shop_goods_item_id,
            shop_id: good?.shop_id,
            num : good.num,
            note: ''
          })
        }
      })
    })
    return info
  })
  // 切换商品状态
  const toggleGoodsStatus = (index, gIndex) => {
    cartList.value[index].goods[gIndex].checked = !cartList.value[index].goods[gIndex].checked
  }
  // 监听选中的商品
  watch(() => selectedInfo.value.sku, (val) => {
    getPayment()
  },{immediate: false})
  // 获取选中的商品的金额参数
  const getPayment = () => {
    const { token } = useUserStore()
    if (!token) return
    getCartListApi({sku: selectedInfo.value.sku, use_integral: 1}).then(res => {
      payment.value = res?.pay_amount
      total_price.value = res?.goods_amount
      discount.value = res?.goods_discount
    })
  }
  // 获取购物车列表
  const getCartList = () => {
    const { token } = useUserStore()
    if (!token) return
    getCartListApi().then(res => {
      res?.shop_lists.forEach((item) => {
        item.goods.forEach((good) => {
          cartList.value.forEach((cItem) => {
            cItem.goods.forEach((cGood) => {
              if (good.sku === cGood.sku) good.checked = cGood.checked
            })
          })
        })
      })
      cartList.value = res?.shop_lists
    })
  }
  // 退出登录是调用
  const clearCart = () => {
    cartList.value = []
    total_price.value = 0
    discount.value = 0
    payment.value = 0
  }
  return {
    payment,
    discount,
    total_price,
    cartList,
    cartNum,
    selectedInfo,
    getCartList,
    toggleGoodsStatus,
    clearCart
  }
}, {
  persist: true
})